  <script setup>
  import { Edit} from '@element-plus/icons-vue'
  import { ref,nextTick  } from 'vue'
  import moment from 'moment';
  import { ElMessage, ElMessageBox } from "element-plus";
  import { attendancePageService, updateAttendanceRemarkService,getWorkTimeConfigService ,updateWorkTimeConfigService} from "@/api/attendance";
  import AMapLoader from '@amap/amap-jsapi-loader'; // 引入高德地图加载器
  // 搜索条件
  const searchForm = ref({
    employeeName: '',
    attendanceType: '',
    status: '',
  })

  // 地图弹窗控制
  const mapDialogVisible = ref(false)
  const currentPosition = ref({ lng: 0, lat: 0 }) // 确保变量在顶层声明

  // 初始化地图
  let map = null
  const initMap = async () => {
    if (!document.getElementById('map-container')) {
      console.error('地图容器未找到')
      return
    }
    
    try {
      const AMap = await AMapLoader.load({
        key: '	af64e6b0a16faf7463ec5aa0a9701544', // 替换为真实 API Key
        version: '2.0',
        plugins: ['AMap.Marker'],
        securityJsCode: '027071d5e5e69b5cceb2e1d515ebd810' 
      })
      
      // 确保地图实例未重复创建
      if (map) map.destroy()
      
      map = new AMap.Map('map-container', {
        zoom: 16,
        center: [currentPosition.value.lng, currentPosition.value.lat]
      })
      
      new AMap.Marker({
        position: [currentPosition.value.lng, currentPosition.value.lat],
        map: map
      })
    } catch (error) {
      console.error('地图加载失败:', error)
    }
  }

  // 点击查看位置按钮
  const handleViewLocation = (row) => {
    currentPosition.value = { // 直接操作 .value
      lng: row.longitude,
      lat: row.latitude
    }
    mapDialogVisible.value = true
  }

  // 关闭地图弹窗时销毁地图
  const handleMapClose = () => {
    if (map) {
      map.destroy()
      map = null
    }
  }
  // 分页数据
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
 //当每页条数发生了变化，调用此函数
 const onSizeChange = (size) => {
  pageSize.value = size
  getAttendanceList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  getAttendanceList()
}
  // 考勤数据
  const attendanceData = ref([
    {
      id: '',
      employeeName: '',
      clockTime: '',
      longitude: '',
      latitude: '',
      attendanceType: '',
      status: '',
      remark: ''
    },
  ])

  // 打卡类型选项
  const typeOptions = [
    { label: '上班打卡', value: 0 },
    { label: '下班打卡', value: 1 }
  ]

  // 状态选项
  const statusOptions = [
    { label: '正常', value: 0 },
    { label: '迟到', value: 1 },
    { label: '早退', value: 2 },
    { label: '缺勤', value: 3 },
    { label: '请假', value: 4 },
    { label: '"未下班打卡"', value: 5 }
  ]

  // 获取考勤列表
  const getAttendanceList = async () => {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      employeeName: searchForm.value.employeeName,
      attendanceType: searchForm.value.attendanceType,
      status: searchForm.value.status,
    }
    
    const result = await attendancePageService(params)
    total.value = result.data.total 
    attendanceData.value = result.data.records.map(item => ({
      ...item,
      statusLabel: statusOptions.find(s => s.value === item.status)?.label, // 显示文本
      attendanceType: typeOptions.find(t => t.value === item.attendanceType)?.label,
      status: item.status, 
    }))
  }

    // 处理审批
    const showEditRemark = (row,remark) => {
      ElMessageBox.prompt(
        `请输入备注：`,
          '考勤备注',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValue: remark == '' ?'请输入备注':remark,
            inputPlaceholder: remark == '' ?'请输入备注':remark,
          }
      ).then(async ({ value: remark }) => {
          row.remark = remark;
        const params = {
          id: row.id,
          remark: row.remark
        }
          const result = await updateAttendanceRemarkService(params)
          ElMessage({
          showClose: true,
          message: result.msg ? result.msg :  `备注成功`,
          type: 'success',
        })
        getAttendanceList()
      })
    }
    
    // 控制修改打卡时间弹窗显示
const modifyTimeDialogVisible = ref(false)
// 存储打卡时间配置
const workConfig = ref({
  workTime: '',
  offTime: ''
})

// 获取打卡时间配置
const getWorkTimeConfig = async () => {
  try {
    const result = await getWorkTimeConfigService()
    workConfig.value = result.data
    
  
  } catch (error) {
    console.error('获取打卡时间配置失败:', error)
    ElMessage.error('获取打卡时间配置失败，请检查网络或重试')
  }
}
getWorkTimeConfig()
// 提交修改打卡时间
const submitModifyTime = async () => {
  const result = await updateWorkTimeConfigService(workConfig.value);
      modifyTimeDialogVisible.value = false
      ElMessage({
      showClose: true,
      message: result.description?result.description:"打卡时间修改成功",
      type: 'success',
    })
}


  // 初始化加载
  getAttendanceList()
  </script>

  <template>
    <el-card class="page-container">
      <template #header>
        <div  class="header" style="display: flex; justify-content: space-between; align-items: center;"  >
          <span>考勤管理</span>
          <div style="display: flex; justify-content: center; margin-bottom: 10px;">
              <span>上班时间：{{ workConfig.workTime }}</span>
              <span>下班时间：{{ workConfig.offTime }}</span>
          </div>
          <el-button type="primary" @click="getWorkTimeConfig();  modifyTimeDialogVisible= true" class="modify-button">修改打卡时间</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.employeeName" placeholder="请输入姓名" clearable />
        </el-form-item>

        <el-form-item label="打卡类型">
          <el-select v-model="searchForm.attendanceType" clearable placeholder="请选择" style="width: 102px;">
            <el-option 
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择" style="width: 102px;">
            <el-option 
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="getAttendanceList">搜索</el-button>
          <el-button @click="searchForm = {}">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="attendanceData" stripe>
        <el-table-column prop="employeeName" label="员工" width="200" />
        <el-table-column prop="clockTime" label="打卡时间" width="200">
          <template #default="{row}">
            {{ moment(row.clockTime).format('YYYY-MM-DD HH:mm') }}
          </template>
        </el-table-column>
        <el-table-column label="位置" width="200">
          <template #default="{row}">
            <el-tooltip :content="`经度:${row.longitude} 纬度:${row.latitude}`">
              <el-button 
                type="primary" 
                link
                @click="handleViewLocation(row)"
              >
                查看位置
              </el-button>
            </el-tooltip>
      
          </template>
        </el-table-column>
        <el-table-column prop="attendanceType" label="类型" width="200" />
        <el-table-column prop="statusLabel" label="状态" width="200" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button :icon="Edit" circle plain type="primary" @click="showEditRemark(row,row.remark)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
                    layout="jumper, total, sizes, prev, pager, next" background :total="total"
                    @size-change="onSizeChange"
                    @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
    </el-card>
    <el-dialog
              v-model="mapDialogVisible"
              title="打卡位置"
              width="800px"
              @open="initMap"
              @closed="handleMapClose"
            >
              <div id="map-container"></div>
            </el-dialog>
            <el-dialog
    v-model="modifyTimeDialogVisible"
    title="修改打卡时间"
    width="500px"
  >
    <el-form :model="workConfig">
      <el-form-item label="上班时间">
        <el-time-picker
          v-model="workConfig.workTime"
          placeholder="选择上班时间"
          format="HH:mm"
          value-format="HH:mm"
        />
      </el-form-item>
      <el-form-item label="下班时间">
        <el-time-picker
          v-model="workConfig.offTime"
          placeholder="选择下班时间"
          format="HH:mm"
          value-format="HH:mm"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitModifyTime">确定</el-button>
        <el-button @click="modifyTimeDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  </template>

  <style scoped>
  .page-container {
    min-height: 100%;
  }
  #map-container {
    width: 100%;
    height: 500px; /* 必须明确指定高度 */
  }
  .modify-button {
  /* 可添加更多按钮样式，如边距等 */
  margin-left: 10px; 
}
  </style>